package model

import (
	"gorm.io/gorm/clause"
	"server/common"
	"server/pkg/app"
)

type MinEnv struct {
	Model
	Name string `gorm:"column:name;not null;type:varchar(100);unique" json:"name"`
}

func (env *MinEnv) TableName() string {
	return "env"
}

type BaseEnv struct {
	Model
	Name string `gorm:"column:name;not null;type:varchar(100);unique" json:"name"`

	OwnerID int `json:"owner_id"`
	Owner   Owner

	ProjectID int `json:"project_id"`
	Project   Project
}

// 环境信息表
type Env struct {
	BaseEnv

	Desc string `gorm:"column:desc;type:varchar(300);" json:"desc"`

	Nodes []MinNode `gorm:"many2many:env_node;ForeignKey:ID;References:ID" json:"nodes"`

	Param  string                 `gorm:"param;type:longtext" json:"param"`
	Params map[string]interface{} `gorm:"-" json:"params"`

	NodeParam  string                 `gorm:"node_param;type:longtext" json:"node_param"`
	NodeParams map[string]interface{} `gorm:"-" json:"node_params"`
}

func (env *Env) TableName() string {
	return "env"
}

func (env *Env) Create() error {
	if err := common.DB.Omit("Nodes.*").Create(&env).Error; err != nil {
		return err
	}
	return nil
}

func (env *BaseEnv) List(page *app.Page) ([]BaseEnv, int64) {
	env_list := []BaseEnv{}
	var count int64
	db := common.DB.Debug().Model(Env{}).Preload("Owner").Order("id desc")

	if err := db.Limit(page.Size).Offset((page.Page - 1) * page.Size).Find(&env_list).Offset(-1).Limit(-1).Count(&count).Error; err != nil {
		return env_list, count
	}

	return env_list, count
}

func (env *Env) Info() error {
	if err := common.DB.Where("name = ?", env.Name).Preload(clause.Associations).First(&env).Error; err != nil {
		return err
	}
	return nil
}

func (env *Env) Update() error {
	if err := common.DB.Where("id = ?", env.ID).Omit("Nodes.*").Updates(&env).Error; err != nil {
		return err
	}
	return nil
}

func (env *Env) Delete() error {
	if err := common.DB.Where("name = ?", env.Name).Delete(&env).Error; err != nil {
		return err
	}
	return nil
}
